package com.leecode.xiehf.page_03;

import com.leecode.xiehf.TreeNode;

public class Solution_0114 {
    public static void main(String[] args) {
        Solution_0114 solution = new Solution_0114();
        TreeNode root = new TreeNode(1,
                new TreeNode(2, new TreeNode(3, new TreeNode(4), null), null),
                new TreeNode(5, null, new TreeNode(6)));
        solution.flatten(root);
        System.out.println(root);
    }
    public void flatten(TreeNode root) {
        TreeNode curr = root;
        while (curr != null) {
            if (curr.left != null) {
                TreeNode next = curr.left;
                TreeNode predecessor = next;
                while (predecessor.right != null) {
                    predecessor = predecessor.right;
                }
                predecessor.right = curr.right;
                curr.left = null;
                curr.right = next;
            }
            curr = curr.right;
        }
    }

//    public void flatten(TreeNode root) {
//        if (root == null) {
//            return;
//        }
//        TreeNode left = root.left;
//        TreeNode right = root.right;
//        flatten(left);
//        flatten(right);
//        root.left = null;
//        root.right = left;
//        TreeNode cursor = root;
//        while(cursor.right != null) {
//            cursor = cursor.right;
//        }
//        cursor.right = right;
//    }

}
